<?php
/***********************************************************
 * 字段类型-业务逻辑
 * @作者 pcfcms <1131680521@qq.com>
 * @主页 http://www.pcfcms.com
 * @时间 2021年01月01日
***********************************************************/
namespace app\admin\logic;
use think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
class FieldLogic 
{

    /**
     * 分类管理-单页编辑
     * @param intval $channel_id 模型ID
     * @param intval $ifmain 是否主表、附加表
     * @param intval $aid 表主键ID
     * @param array $archivesinfo 主表数据
     * @param array $suffix 附加表后续名称,可以是数组转入
     */
    public function getChannelFieldList($channel_id, $ifmain = 0, $aid = '', $archivesinfo = [],$suffix = "content")
    {
        $channel_id = intval($channel_id);
        $map = [];
        $map[] = ['channel_id','=',$channel_id];
        $map[] = ['ifmain','<>',1];
		$map[] = ['status','=',1];
        $map[] = ['ifeditable','=',1];
        if (0 != $ifmain) {$map[] = ['ifmain','=',$ifmain];}
        $row = Db::name('channelfield')
                ->where($map)
                ->whereNotIn('name','id,aid,add_time,update_time')
                ->order("sort_order asc")
                ->select()->toArray();
        //编辑时显示的数据
        $addonRow = [];
        $map1 = [];
        $map1[] = ['typeid','=',$aid];
        $map1[] = ['channel','=',$channel_id];
        if (0 < intval($aid)) {
            if (6 == $channel_id) {
                $aid = Db::name('archives')->where($map1)->value('aid');
            }
            $tableExt = Db::name('channel_type')->where('id', $channel_id)->value('table');
            $suffix = explode(',',$suffix);
            foreach ($suffix as $val){
                $temp = Db::name($tableExt.'_'.$val)->field('*')->where('aid', $aid)->find();       
                if(isset($temp)){ $addonRow = array_merge($addonRow,$temp);} 
            }
        }
        $list = $this->showViewFormData($row, 'addonFieldExt', $addonRow, $archivesinfo);
        return $list;
    }

    //查询解析模型数据用以构造from表单
    public function PcfChannelPostData($channel_id, $data = [], $dataExt = [],$suffix = 'content')
    {
        if (!empty($channel_id)) {
            $nowDataExt = [];
            $fieldTypeList = Db::name('channelfield')->where('channel_id', $channel_id)->column('name,dtype', 'name');
            foreach ($dataExt as $key => $val) {
                // 处理复选框取消选中的情况下
                if (preg_match('/^(.*)(_pcfempty)$/', $key) && empty($val)) {
                    $key = preg_replace('/^(.*)(_pcfempty)$/', '$1', $key);
                    continue;
                }
                $key = preg_replace('/^(.*)(_gzpcf_is_remote|_gzpcf_remote|_gzpcf_local)$/', '$1', $key);
                $dtype = !empty($fieldTypeList[$key]) ? $fieldTypeList[$key]['dtype'] : '';
                switch ($dtype) {
                    case 'checkbox':
                    {
                        $val = implode(',', $val);
                        break;
                    }
                    case 'switch':
                    case 'int':
                    {
                        $val = intval($val);
                        break;
                    }
                    case 'img':
                    {
                        $is_remote = !empty($dataExt[$key.'_gzpcf_is_remote']) ? $dataExt[$key.'_gzpcf_is_remote'] : 0;
                        if (1 == $is_remote) {
                            $val = $dataExt[$key.'_gzpcf_remote'];
                        } else {
                            $val = $dataExt[$key.'_gzpcf_local'];
                        }
                        break;
                    }
                    case 'imgs':
                    case 'files':
                    {
                        foreach ($val as $k2 => $v2) {
                            if (empty($v2)) {
                                unset($val[$k2]);
                                continue;
                            }
                            $val[$k2] = trim($v2);
                        }
                        $val = implode(',', $val);
                        break;
                    }
                    case 'datetime':
                    {
                        $val = !empty($val) ? strtotime($val) : 0;
                        break;
                    }
                    case 'decimal':
                    {
                        $moneyArr = explode('.', $val);
                        $money1 = !empty($moneyArr[0]) ? intval($moneyArr[0]) : '0';
                        $money2 = !empty($moneyArr[1]) ? intval(pcf_msubstr($moneyArr[1], 0, 2)) : '00';
                        $val = $money1.'.'.$money2;
                        break;
                    }
                    default:
                    {
                        $val = trim($val);
                        break;
                    }
                }
                if (!empty($val)){
                    $nowDataExt[$key] = $val;
                }else if($val == 0){ 
                    $nowDataExt[$key] = $val;
                }else{
                    $nowDataExt[$key] = $val;
                }
            }
            $nowData = [
                'typeid'   => $data['typeid'],
                'aid'   => $data['aid'],
                'add_time'   => getTime(),
                'update_time'   => getTime()
            ];
            !empty($nowDataExt) && $nowData = array_merge($nowDataExt, $nowData);
            //过滤带有_pcfempty字段
            foreach ($nowData as $key => $value) {
                if(strpos($key,'_pcfempty')){unset($nowData[$key]);}
            }
            $tableExt = Db::name('channel_type')->where('id', $channel_id)->value('table');
            $tableExt .= '_'.$suffix;
            $count = Db::name($tableExt)->where('aid', $data['aid'])->count();
            if (empty($count)) {
                Db::name($tableExt)->insert($nowData);// 添加
            } else {
                Db::name($tableExt)->where('aid', $data['aid'])->save($nowData);// 编辑
            }
        }
    }

    /**
     * 处理显示自定义字段的表单数据
     * @param array $list 自定义字段列表
     * @param array $formFieldStr 表单元素名称
     * @param array $addonRow 自定义字段的数据
     * @param array $archivesinfo 主表数据
     */
    private function showViewFormData($list, $formFieldStr, $addonRow = [], $archivesinfo = [])
    {
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $val['fieldArr'] = $formFieldStr;
                switch ($val['dtype']) {
                    case 'int': // 整数类型
                    {
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['dfvalue'] = $addonRow[$val['name']];
                        } else {
                            if(preg_match("#[^0-9]#", $val['dfvalue']))
                            {
                                $val['dfvalue'] = "";
                            }
                        }
                        break;
                    }
                    case 'float':// 小数类型
                    case 'decimal':// 金额类型
                    {
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['dfvalue'] = $addonRow[$val['name']];
                        } else {
                            if(preg_match("#[^0-9\.]#", $val['dfvalue']))
                            {
                                $val['dfvalue'] = "";
                            }
                        }
                        break;
                    }
                    case 'select':// 下拉框
                    case 'radio':// 单选项
                    {
                        $dfvalue = $val['dfvalue'];
                        $dfvalueArr = explode(',', $dfvalue);
                        $val['dfvalue'] = $dfvalueArr;
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['trueValue'] = explode(',', $addonRow[$val['name']]);
                        } else {
                            $dfTrueValue = !empty($dfvalueArr[0]) ? $dfvalueArr[0] : '';
                            $val['trueValue'] = array($dfTrueValue);
                        }
                        break;
                    }
                    case 'checkbox':// 多选项
                    {
                        $dfvalue = $val['dfvalue'];
                        $dfvalueArr = explode(',', $dfvalue);
                        $val['dfvalue'] = $dfvalueArr;
                        if (array_key_exists($val['name'], $addonRow)) {
                            $val['trueValue'] = explode(',', $addonRow[$val['name']]);
                        } else {
                            $val['trueValue'] = array();
                        }
                        break;
                    }
                    case 'datetime':// 日期和时间
                    {
                        $val['dfvalue'] = !empty($addonRow[$val['name']]) ? date('Y-m-d H:i:s', $addonRow[$val['name']]) : '';
                        break;
                    }                    
                    case 'img':// 单图
                    {
                        $val[$val['name'].'_gzpcf_is_remote'] = 0;
                        $val[$val['name'].'_gzpcf_remote'] = '';
                        $val[$val['name'].'_gzpcf_local'] = '';
                        if (array_key_exists($val['name'], $addonRow)) {
                            if (is_http_url($addonRow[$val['name']])) {
                                $val[$val['name'].'_gzpcf_is_remote'] = 1;
                                $val[$val['name'].'_gzpcf_remote'] = handle_subdir_pic($addonRow[$val['name']]);
                            } else {
                                $val[$val['name'].'_gzpcf_is_remote'] = 0;
                                $val[$val['name'].'_gzpcf_local'] = handle_subdir_pic($addonRow[$val['name']]);
                            }
                        }
                        break;
                    }
                    case 'imgs':// 多图
                    {
                        $val[$val['name'].'_gzpcf_imgupload_list'] = [];
                        if (array_key_exists($val['name'], $addonRow) && !empty($addonRow[$val['name']])) {
                            $imgupload_list = explode(',', $addonRow[$val['name']]);
                            foreach ($imgupload_list as $k1 => $v1) {
                                $imgupload_list[$k1] = handle_subdir_pic($v1);
                            }
                            $val[$val['name'].'_gzpcf_imgupload_list'] = $imgupload_list;
                        }
                        break;
                    }
                    case 'htmltext':// HTML文本
                    {
                        $val['dfvalue'] = isset($addonRow[$val['name']]) ? $addonRow[$val['name']] : $val['dfvalue'];
                        if (!empty($archivesInfo['title'])) {
                            $title = $archivesInfo['title'];
                        } else {
                            $title = !empty($archivesInfo['typename']) ? $archivesInfo['typename'] : '';
                        }
                        $content = htmlspecialchars_decode($val['dfvalue']);// 预定义转义
                        $val['dfvalue'] = htmlspecialchars(img_style_wh($content, $title));
                        $val['dfvalue'] = handle_subdir_pic($val['dfvalue'], 'html');
                        break;
                    }
                    default: // 其它类型
                    {
                        $val['dfvalue'] = array_key_exists($val['name'], $addonRow) ? $addonRow[$val['name']] : $val['dfvalue'];
                        if (is_string($val['dfvalue'])) {
                            $val['dfvalue'] = handle_subdir_pic($val['dfvalue'], 'html');
                            $val['dfvalue'] = handle_subdir_pic($val['dfvalue']);
                        }
                        break;
                    }
                }
                $list[$key] = $val;
            }
        }
        return $list;
    }


















    /////////////////////////////////////////////////////////////////////////////////////////////////






    /**
     * 查询解析数据表的数据用以构造from表单- 没有用到的地方
     * @param intval $channel_id 模型ID
     * @param intval $id 表主键ID
     */
    public function getTabelFieldList($channel_id, $id = '')
    {
        $channel_id = intval($channel_id);
        $map = [];
        $map[] = ['channel_id','=',$channel_id];
        $map[] = ['ifsystem','=',0];
        $row = Db::name('channelfield')
                ->where($map)
                ->whereNotIn('name','id,aid,add_time,update_time')
                ->select()->toArray();
        //编辑时显示的数据
        $addonRow = [];
        if (0 < intval($id)) {
            if (config('pcfcms.arctype_channel_id') == $channel_id) {
                $addonRow = Db::name('arctype')->field('*')->where('id', $id)->find();
            }
        }
        $list = $this->showViewFormData($row, 'addonField', $addonRow);
        return $list;
    }


    //获取全部字段类型
    public function getFieldTypeAll($field = '*', $index_key = '')
    {
        $cacheKey = "admin-Field-getFieldTypeAll-{$field}-{$index_key}";
        $result = cache::get($cacheKey);
        if (empty($result)) {
            $result = Db::name('field_type')->field($field)->order('sort_order asc')->select()->toArray();
            if (!empty($index_key)) {
                $result = convert_arr_key($result, $index_key);
            }
            Cache::tag('admin-Field-getFieldTypeAll')->set($cacheKey, $result, ADMIN_CACHE_TIME);
        }
        return $result;
    }


}